package com.chen.jwt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.jwt.mapper.UsersMapper;
import com.chen.jwt.pojo.Users;

import com.chen.jwt.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class JwtController {
    @Resource
    private UsersMapper mapper;

    // 认证
    @PostMapping("/user/login")
    public Map<String,Object> login(Users user) {
        System.out.println("前端传来的用户数据："+user);
        // 返回结果
        Map<String,Object> result = new HashMap<>();
        try {
            // 查询数据库
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            HashMap<String, Object> queryMap = new HashMap<>();
            queryMap.put("username", user.getUsername());
            queryMap.put("password", user.getPassword());
            queryWrapper.allEq(queryMap);
            Users userDB = mapper.selectOne(queryWrapper);
            // 认证失败
            if(userDB == null)
                throw new RuntimeException("没有此用户。请重新登录");

            // 认证成功
            Map<String, String> tokenClaimsMap = new HashMap<>(); //用来存放payload
            tokenClaimsMap.put("id",userDB.getId());
            tokenClaimsMap.put("username", userDB.getUsername());
            String token = JWTUtils.getToken(tokenClaimsMap);
            // 返回的数据
            result.put("state",true);
            result.put("msg","登录成功!");
            result.put("token",token);
        } catch (Exception e) {
            // 认证失败，返回的数据
            e.printStackTrace();
            result.put("state","false");
            result.put("msg",e.getMessage());
        }
        return result;
    }

    @GetMapping("/private/info")
    public String info(HttpServletRequest request){
        String token = request.getHeader("token");
        DecodedJWT decodedJWT = JWTUtils.getToken(token);
        System.out.println(decodedJWT.getClaim("username").asString());
        System.out.println(decodedJWT.getClaim("userId").asInt());
        return "这是一段私人信息。只有登录才能显示";
    }
}
